#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

SeqList::SeqList(int n)
{
	_arr = (SLDataType*)malloc(sizeof(SLDataType) * n);
	_size = 0;
	_capacity = 0;
}
SeqList::~SeqList()
{
	free(_arr);
	_arr = NULL;
	_size = _capacity = 0;
}


void SeqList::SeqListPushBack(SLDataType x)
{
	if (_size == _capacity)
	{
		int newCapacity = _capacity == 0 ? 4 : _capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(_arr, sizeof(SLDataType) * newCapacity);
		if (tmp == nullptr)
		{
			perror("realloc fail");
			return;
		}
		_arr = tmp;
		_capacity = newCapacity;
	}

	_arr[_size++] = x;

}
void SeqList::SeqListPushFront(SLDataType x)
{
	if (_size == _capacity)
	{
		int newCapacity = _capacity == 0 ? 4 : _capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(_arr, sizeof(SLDataType) * newCapacity);
		if (tmp == nullptr)
		{
			perror("realloc fail");
			return;
		}
		_arr = tmp;
		_capacity = newCapacity;
	}

	int end = _size;
	while (end > 0)
	{
		_arr[end] = _arr[end - 1];
		end--;
	}

	_arr[0] = x;
	_size++;
}
void SeqList::SeqListPrint()
{
	for (int i = 0; i < _size; i++)
	{
		cout << _arr[i] << " ";
	}
	cout << endl;
}
void SeqList::SeqListPopBack()
{
	_size--;
}
void SeqList::SeqListPopFront()
{
	int start = 0;
	while (start < _size)
	{
		_arr[start] = _arr[start + 1];
		start++;
	}
	_size--;
}

int SeqList::SeqListFind(SLDataType x)
{
	for (int i = 0; i < _size; i++)
	{
		if (_arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}
void SeqList::SeqListInsert(SLDataType x, int pos)
{
	int end = _size;
	while (end > pos)
	{
		_arr[end] = _arr[end - 1];
		end--;
	}
	_arr[pos] = x;
	_size++;
}
void SeqList::SeqListErase(int pos)
{
	int start = pos;
	while (pos < _size)
	{
		_arr[pos] = _arr[pos + 1];
		pos++;
	}

	_size--;
}
